<?php
/**
*	@method init_fb_sdk()
*	@method getUserID()
*	@method getLoginLogout(): render login/logout html
*	@method getFriendsIds(): Get all friend-ids of current user
*	@method getAccessToken(): Get fresh access token from user (oauth)
*	@method getUser()
*	@method getUserID()
*	@method setUserCredentials(): fill attributes, register user
*
*/

class Facebookcontroller {
	
	private $dbcon;
	private $facebook;
	
	private $uid;
	private $accestoken;
	
	private $user;
	
    public function  __construct($_dbcon)
    {
        $this->dbcon = $_dbcon;
		$this->init_fb_sdk();
    }
    
    private function init_fb_sdk(){
    	
    	$config = array(
    		"appId" => $this->dbcon->getSettingValue("fb_appid"),
    		"secret" => $this->dbcon->getSettingValue("fb_appsecret"),
    		"fileUpload" => false,
    	
    	);
    	
    	$this->facebook = new Facebook($config);
    
    }
    
    public function getUserID(){
    	return $this->uid;
    }
    /**
    *	Use to render login or logout link
    */
    public function getLoginLogout(){
   
	    try{
	    	if(!$this->setUserCredentials()){
	    		$params = array(
	    			'redirect_uri' => 'http://soofie.be/jill/twofifty/mylist.php',
	    			'display' => 'popup'
	    		);
	    		echo "<a href=".$this->facebook->getLoginUrl($params).">Login</a>";
	    	}
	    	else
	    		echo "<a href=".$this->facebook->getLogoutUrl()." value=".$this->uid.">Logout</a>";  
	    	
	    }
	    catch(FacebookApiException $fe){
	    		
	    		echo "<script>safelog(".$fe.");</script>";
	    		//error_log($e);
	    }
	    catch(Exception $e){
	    	
	    		echo "<script>safelog(".$e.");</script>";
	    		error_log($e);
	    }
    	   	
    }
      
    public function setUserCredentials(){
    	
    	try{
    	
    		$user = $this->getUser();
    		    		
    		if($user && $user != 0)
    		{
    			$this->uid = $user;
    			$this->accesstoken = $this->getAccessToken(); 
    			$this->user = $this->facebook->api('me/', 'GET');
    			$this->registerUser($this->uid, $this->user['username']);
    			return true;
    		}
    		else
    			return false;
    		   	
    	}
    	catch(FacebookApiException $fe){
	    		echo "<script>safelog('$fe');</script>";
	    		//error_log($e);
	    }
	    catch(Exception $e){
	    		echo "<script>safelog('$e');</script>";
	    		//error_log($e);
	    }
    	  
    	
    }
    
    /**
    *	This method returns the Facebook User ID of the current user, 
    *	or 0 if there is no logged-in user.
    */
   	public function getUser(){
   		
   		return $this->facebook->getUser();
   	
   	}
   	
   	public function getAccessToken(){
   		
   		return $this->facebook->getAccessToken();
   		
   	}
   	/**
   	*	Get all friend-ids of current user
   	*
   	*	@return array array(id => name); //sorted by id
   	*/
   	public function getFriendsIds(){
   		
   		try{
   			$allinfo =  $this->facebook->api('/me/friends', array('access_token'=>$this->accestoken));
   			$friends = $allinfo["data"];
   			$ids = array();
   			
   			foreach($friends as $friend){
   				$ids[(int) $friend["id"]] = $friend["name"];
   			}
   			return $ids;
   		}
   		catch(FacebookApiException $fe){
	    		echo "<script>safelog('$fe');</script>";
	    		//error_log($e);
	    }
	    catch(Exception $e){
	    		echo "<script>safelog('$e');</script>";
	    		//error_log($e);
	    }
    	  
    	
   	}
   	/**
   	*	Register user if user is new
   	*/
   	public function registerUser($uid, $name){
		
		$this->dbcon->registerUser($uid, $name);
	
	}
   
   /**
   *	Compare users FB-friends, with registered users in the database
   *	Adds current user to list
   *
   *	@return array $registeredFriendsKeys
   */
   	public function checkForFriendsInDb(){
   		
   		if($this->getUser() == 0)
   			return null; 
   			
   		$registeredFriends = array();
   		$allFriends = $this->getFriendsIds();
   		$dbids = array();
   		
   		$resultset = $this->dbcon->selectQuery("user", array("fbid")); 
   		
   		if(!$resultset)
        	return null;
        	
        while ($row = $resultset->fetch_object()){

            $dbids[intval($row->fbid)] = intval($row->fbid);

        }
        
        $registeredFriendsKeys = array();
		
		//add current user to list
		$registeredFriendsKeys[$this->getUserID()] = $this->user["name"];
		
        foreach($allFriends as $id => $name)
        {
        	if($dbids[$id])
        		$registeredFriendsKeys[$id] = $name;
        }
        return $registeredFriendsKeys;
   	
   	}
   	
   	
   	
    


}
?>